class Solution {
    public long continuousSubarrays(int[] nums) {
        long ans = 0;
        Queue<int[]> minQueue = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[1] - o2[1];
            }
        });
        Queue<int[]> maxQueue = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o2[1] - o1[1];
            }
        });
        var left = 0;
        var right = 0;
        while(right<nums.length){
            minQueue.offer(new int[]{right,nums[right]});
            maxQueue.offer(new int[]{right,nums[right]});
            while(!minQueue.isEmpty() && !maxQueue.isEmpty()){
                while (!maxQueue.isEmpty() && maxQueue.peek()[0] < left){
                    maxQueue.poll();
                }
                while (!minQueue.isEmpty() && minQueue.peek()[0] < left){
                    minQueue.poll();
                }
                var min = minQueue.peek();
                var max = maxQueue.peek();
                if(max[1]-min[1]>2){
                    left++;
                }else{
                    break;
                }
            }
            ans += right - left + 1;
            right++;
        }
        return ans;
    }
}